package com.microservice.salmon.oauth.jwt;

import com.microservice.salmon.oauth.client.ClientInfo;
import com.microservice.salmon.oauth.client.ClientProcessorHolder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

public class SalmonJwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        // org.springframework.security.core.userdetails.User
        // User user = (User)authentication.getPrincipal();
        ClientInfo clientInfo =  ClientProcessorHolder.getClientInfo();//直接从threadLocal中获取
        String realName = clientInfo.getRealName();
        Map<String, Object> info = new HashMap<>();
        info.put("name", realName);
        info.put("photo", clientInfo.getPhoto());
        info.put("userId", clientInfo.getUserId());
        if(clientInfo.getRoleId() != null){
            info.put("roleId", clientInfo.getRoleId());
        }
        if(clientInfo.getShopId() != null){
            info.put("shopId", clientInfo.getShopId());
        }
        ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
